<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
        }
        .progress-wrapper {
            height: 10px;
            width: 100vw;
            background-color: #aaa;
        }
        .progress-wrapper .progress {
            height: 10px;
            width: 0;
            transition: 0.2s linear;
            background-color: red;
        }
    </style>
</head>
<body>
    <input type="file">
    <button>上传</button>

    <div class="progress-wrapper">
        <div class="progress"></div>
    </div>

    <script>

        const url = 'http://www.liulongbin.top:3006/api/upload/avatar';

        const inp = document.querySelector('input');
        const btn = document.querySelector('button');
        const progressBox = document.querySelector('.progress');

        btn.addEventListener('click', () => {
            // const files = inp.files;
            // es6 对象解构赋值
            const { files } = inp;
            console.log(files);

            // 判断  大于500k不能上传
            // if (files[0].size > 500 * 1024) {
            //     alert('大于500k不能上传');
            //     return;
            // }

            const fd = new FormData();
            fd.append('嘿嘿', files[0]);

            const xhr = new XMLHttpRequest();
            xhr.open('POST', url);

            // 监听状态改变
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 当状态值为4(最后阶段)时 && 请求成功时
                    console.log(JSON.parse(xhr.responseText));

                }
            };
            // 文件上传 必须在发送之前绑定
            xhr.upload.onprogress = function (e) {
                const progress = e.loaded / e.total; // 0.8
                progressBox.setAttribute('style', `width: ${progress * 100}%`);
            };

            // 发送
            xhr.send(fd);

        });

    </script>
</body>
</html>